﻿using System;
 using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace GameFx
{
    public abstract partial class Game : Application
    {
        public Game()
        {
            this.Startup += this.Application_Startup;
            this.Exit += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;
            LoadContent();
            //updateStoryBoard = new Storyboard();
            //updateStoryBoard.Completed += update;
            //updateStoryBoard.Begin();
            //drawStoryBoard = new Storyboard();
            //drawStoryBoard.Completed += draw;
            //drawStoryBoard.Begin();

            
        }

        Storyboard updateStoryBoard;
        Storyboard drawStoryBoard;
        int last_second;
        int second;
        protected int Fps { get; private set; }
        int new_fps;
        DateTime start;

        private bool started = false;

        protected Canvas GameSurface { get; private set; }
        protected KeyboardState KeyboardState { get; private set; }

        void update(object sender, EventArgs e)
        {
            if (second != DateTime.Now.Second)
            {
                last_second = second;
                Fps = new_fps;
                new_fps = 0;
                second = DateTime.Now.Second;
            }
            new_fps++;

            //FPS.Text = fps.ToString();
            var gameTime = new GameTime();
            Update(gameTime);
            updateStoryBoard.Begin();
        }

        void CompositionTarget_Rendering(object sender, EventArgs e)
        {
            if (second != DateTime.Now.Second)
            {
                last_second = second;
                Fps = new_fps;
                new_fps = 0;
                second = DateTime.Now.Second;
            }
            new_fps++;

            //if (started)
            //{
                var gameTime = new GameTime();
                gameTime.Time = DateTime.Now - start;
                Update(gameTime);
                Draw(gameTime);
            //}
        }

        public void Start()
        { 
            
        }

        //void draw(object sender, EventArgs e)
        //{
        //    //FPS.Text = fps.ToString();
        //    var gameTime = new GameTime();
        //    gameTime.Time = DateTime.Now - start;
        //    Draw(gameTime);
        //    drawStoryBoard.Begin();
        //}

        protected ContentManager ContentManager { get; private set; }

        public abstract void LoadContent();
        public abstract void UnloadContent();
        public abstract void Update(GameTime gameTime);
        public abstract void Draw(GameTime gameTime);

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            GameSurface = new Canvas
            {
                Height = 768,
                Width = 1024,
                HorizontalAlignment = HorizontalAlignment.Center,
                VerticalAlignment = VerticalAlignment.Center
            };
            KeyboardState = new KeyboardState();
            var layoutRoot = new Grid
            {
                HorizontalAlignment = HorizontalAlignment.Stretch,
                VerticalAlignment = VerticalAlignment.Stretch,
            };
            GameSurface.SetValue(Clip.ToBoundsProperty, true);
            layoutRoot.Children.Add(GameSurface);
            RootVisual = layoutRoot;
            layoutRoot.KeyDown += new KeyEventHandler(GameSurface_KeyDown);
            layoutRoot.KeyUp += new KeyEventHandler(GameSurface_KeyUp);
            if (!Application.Current.IsRunningOutOfBrowser)
                System.Windows.Browser.HtmlPage.Plugin.Focus();
            CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering);
            start = DateTime.Now;
        }

        void GameSurface_KeyUp(object sender, KeyEventArgs e)
        {
            if (!KeyboardState.ContainsKey(e.Key))
                KeyboardState.Add(e.Key, false);
            else
                KeyboardState[e.Key] = false;
        }

        void GameSurface_KeyDown(object sender, KeyEventArgs e)
        {
            if (!KeyboardState.ContainsKey(e.Key))
                KeyboardState.Add(e.Key, true);
            else
                KeyboardState[e.Key] = true;
        }

        private void Application_Exit(object sender, EventArgs e)
        {

        }
        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (!System.Diagnostics.Debugger.IsAttached)
            {
                e.Handled = true;
                Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); });
            }
        }
        private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
        {
            try
            {
                string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
                errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n");

                System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight 2 Application " + errorMsg + "\");");
            }
            catch (Exception)
            {
            }
        }
    }
}
